<template>
  <div class="app-container">
    <el-card>
      <title-line title="基本信息" />
      <el-form ref="elForm" :model="formData" :rules="rules" label-width="100px">
        <el-row>
          <el-col :lg="12" :xl="10">
            <el-form-item label="广告名称：" prop="bannerName">
              <el-input
                v-model="formData.bannerName"
                placeholder="请输入广告名称（2-20个字）`"
                clearable
              />
            </el-form-item>
            <el-form-item label="广告位置：" prop="placeId">
              <el-select
                v-model="formData.placeId"
                placeholder="请选择广告位置"
                clearable
                style="width: 100%"
              >
                <el-option
                  v-for="(item, index) in advertPlace"
                  :key="index"
                  :label="item.placeName"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="广告图片：" prop="bannerImg">
              <UploadImage
                :isShowTip="true"
                :file-type="['jpg', 'png', 'jpeg']"
                file-pixel="600*400"
                :file-size="1"
                :limit="1"
                :response-fn="handleResponse"
                @on-change="uploadChange"
                v-model="formData.bannerImg"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :lg="16" :xl="14">
            <el-form-item label="指向位置：" prop="pointPlace">
              <PointPosition ref="PointPosition" v-model="formData" :isTherePlatform="true" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :lg="12" :xl="10">
            <el-form-item label="投放时间：" prop="timeRule">
              <el-row>
                <el-col :lg="10" :xl="8">
                  <el-radio-group v-model="formData.timeRule">
                    <el-radio
                      v-for="(item, index) in APPOINT_TIME_STATUS"
                      :key="index"
                      :label="item.value"
                    >
                      {{ item.label }}
                    </el-radio>
                  </el-radio-group>
                </el-col>
                <el-col :lg="14" :xl="16">
                  <el-date-picker
                    v-if="!formData.timeRule"
                    type="datetimerange"
                    :picker-options="pickerOptions"
                    v-model="time"
                    format="yyyy-MM-dd HH:mm:ss"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    range-separator="至"
                    clearable
                  />
                </el-col>
              </el-row>
            </el-form-item>
            <el-form-item label="排序位置：" prop="sort">
              <el-input v-model="formData.sort" placeholder="请输入排序位置" clearable />
              <p style="color: #909399; font-size: 12px">数字越小排序越靠前</p>
            </el-form-item>
            <el-form-item label="是否启用：" prop="isShow">
              <el-radio-group v-model="formData.isShow">
                <el-radio v-for="(item, index) in ENABLE_STATUS" :key="index" :label="item.value">
                  {{ item.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item>
          <el-button @click="resetForm"> 取消 </el-button>
          <el-button type="primary" @click="submitForm"> 确定 </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import addRules from './rules'
import { PointPosition } from '@components'
import { parseTime, useValidatepointPlace } from '@/hooks'
import { APPOINT_TIME_STATUS, ENABLE_STATUS, POPUP_PLACE_LABEL, REGION_TYPE } from '@/enum/advert'
export default {
  name: 'AddAdvert',
  components: {
    PointPosition
  },
  data() {
    return {
      dialogVisible: false,
      formData: {
        sort: 99,
        bannerName: '',
        placeId: '',
        pointPlace: 0,
        targetParam: '',
        isShow: true,
        bannerImg: '',
        timeRule: 1,
        iconThreePoint: '',
        outsideType: ''
      },
      time: [],
      advertPlace: [],
      listQuery: {
        pageNo: 1,
        pageSize: 10
      },
      // 选择开始时间大于等于当前时间
      pickerOptions: {
        disabledDate(time) {
          const dateTime = new Date()
          const startDateTime = dateTime.setDate(dateTime.getDate() - 1)
          const endDateTime = dateTime.setDate(dateTime.getDate() + 30000) //30000为当前日期之后多少天
          return (
            time.getTime() < new Date(startDateTime).getTime() ||
            time.getTime() > new Date(endDateTime).getTime()
          )
        },
        selectableRange:
          //setMinutes,getMinutes限制分 , 年、月、日、时、分、秒同理,+1为数字区间
          parseTime(new Date().setMinutes(new Date().getMinutes() + 1), '{hh}:{ii}:{ss}') +
          '- 23:59:00'
      }
    }
  },
  computed: {
    rules() {
      return {
        bannerName: [
          {
            required: true,
            message: '请输入广告名称',
            trigger: 'blur'
          },
          {
            min: 2,
            max: 20,
            message: '广告名称限制2-20个字'
          }
        ],
        ...addRules
      }
    },
    REGION_TYPE() {
      return REGION_TYPE
    },
    ENABLE_STATUS() {
      return ENABLE_STATUS
    },
    APPOINT_TIME_STATUS() {
      return APPOINT_TIME_STATUS
    },
    POPUP_PLACE_LABEL() {
      return POPUP_PLACE_LABEL
    },
    id() {
      return this.$route.query?.id
    }
  },
  watch: {
    'formData.timeRule'(val) {
      if (val) {
        this.time = []
      }
    }
  },
  created() {
    this.getAdvertPlace()
    this.getAdvertDetail()
  },
  methods: {
    // 获取广告位置
    async getAdvertPlace() {
      const { data } = await this.$http.advert.placeApi.getPlaceSelect()
      this.advertPlace = data
    },
    // 校验指向时间
    validatepointTime() {
      const timeStart = this.time && this.time[0]
      const timeEnd = this.time && this.time[1]
      if (!(timeStart && timeEnd) && !this.formData.timeRule) {
        this.$message.error('请选择投放时间！')
        return false
      }

      let flag

      const start_date = this.$moment(timeStart, 'YYYY-MM-DD HH:mm:ss')
      const end_date = this.$moment(timeEnd, 'YYYY-MM-DD HH:mm:ss')
      const hours = end_date.diff(start_date, 'minutes')
      if (hours < 30) {
        this.$message.error('投放结束时间要大于投放开始时间半小时！')
        flag = false
      } else {
        flag = true
      }
      return flag
    },
    // 获取参数
    getParams() {
      if (this.formData.pointPlace === 4) {
        if (!this.formData.outsideType) {
          return this.$message.warning('请选择第三方平台')
        } else if (this.formData.outsideType && !this.formData.iconThreePoint) {
          return this.$message.warning('请填写指向路径')
        }
      }

      const params = {
        ...this.formData
      }
      console.log(params, 'params.pointPlace')
      if (this.time) params.timeStart = this.time[0]
      if (this.time) params.timeEnd = this.time[1]
      if (this.id) params.id = this.id
      if (params.pointPlace == 4) {
        delete params.pointPlace
      } else {
        delete params.iconThreePoint
        delete params.outsideType
      }
      console.log(params, 'params====')
      return params
    },
    // 获取详情
    async getAdvertDetail() {
      if (!this.id) return
      const { data } = await this.$http.advert.advertApi.getAdvertDetail(this.id)
      for (const key in this.formData) {
        if (key === 'pointPlace') {
          this.formData[key] = parseInt(data[key])
        } else if (key === 'timeRule') {
          this.formData[key] = data[key] ? 1 : 0
        } else {
          this.formData[key] = data[key]
        }
      }
      this.$refs.PointPosition.loadPointData(this.formData)
      this.time = [data.timeStart ? data.timeStart : '', data.timeEnd ? data.timeEnd : '']
      if (!this.formData.pointPlace && this.formData.outsideType) {
        this.formData.pointPlace = 4
      }
    },
    // 新增广告
    async addAdvert() {
      const params = this.getParams()
      const { status, msg } = await this.$http.advert.advertApi.addAdvert(params)
      if (status === 200) {
        this.$message.success('新增成功')
        this.$router.back(-1)
      } else {
        this.$message.error(msg)
      }
    },
    // 编辑广告
    async updateAdvert() {
      const params = this.getParams()
      const { status, msg } = await this.$http.advert.advertApi.updateAdvert(params)
      if (status === 200) {
        this.$message.success('编辑成功')
        this.$router.back(-1)
      } else {
        this.$message.error(msg)
      }
    },
    // 提交
    submitForm() {
      this.$refs['elForm'].validate(valid => {
        if (!valid) return

        // 校验指向位置
        let flag1 = useValidatepointPlace(this.formData)
        if (!flag1) return

        // 校验投放时间
        let flag2 = this.validatepointTime()
        if (!flag2) return

        if (!this.id) {
          this.addAdvert()
        } else {
          this.updateAdvert()
        }
      })
    },
    uploadChange() {
      if (this.formData.bannerImg) {
        this.$refs.elForm.validateField('bannerImg')
      }
    },
    resetForm() {
      this.$refs['elForm'].resetFields()
      this.$router.back(-1)
    },
    handleResponse(response) {
      return response
    }
  }
}
</script>
<style>
.el-upload__tip {
  line-height: 1.2;
}
</style>
